import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'

// Element Plus
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import zhCn from 'element-plus/dist/locale/zh-cn.mjs'
import * as ElementPlusIconsVue from '@element-plus/icons-vue'

// 禁用所有 console 输出（生产环境）
if (process.env.NODE_ENV !== 'development') {
  console.log = function() {}
  console.info = function() {}
  console.debug = function() {}
  console.warn = function() {}
}

// 开发环境保留console输出
if (process.env.NODE_ENV === 'production') {
  console.log = function() {}
  console.info = function() {}
  console.debug = function() {}
  console.warn = function() {}
}

// 完全忽略 ResizeObserver 相关错误（Element Plus 已知问题，不影响功能）
// 重写 ResizeObserver 以避免循环错误
const resizeObserverErrorHandler = (e) => {
  if (e.message === 'ResizeObserver loop completed with undelivered notifications.' ||
      e.message === 'ResizeObserver loop limit exceeded') {
    const resizeObserverErr = document.getElementById('webpack-dev-server-client-overlay')
    if (resizeObserverErr) {
      resizeObserverErr.style.display = 'none'
    }
  }
}
window.addEventListener('error', resizeObserverErrorHandler)

// 拦截全局错误
window.onerror = function (message, source) {
  const errorMessage = message ? message.toString() : ''
  const sourceStr = source ? source.toString() : ''
  // 忽略 ResizeObserver、getComputedStyle 和 overlay 相关错误
  if (errorMessage.includes('ResizeObserver') || 
      errorMessage.includes('getComputedStyle') ||
      errorMessage.includes('parameter 1 is not of type') ||
      errorMessage.includes('loop completed with undelivered notifications') ||
      sourceStr.includes('overlay')) {
    return true // 阻止错误传播
  }
  return false
}

// 忽略未捕获的 Promise 错误
window.addEventListener('unhandledrejection', (event) => {
  const reason = event.reason
  if (reason && reason.message) {
    const message = reason.message.toString()
    if (message.includes('ResizeObserver') ||
        message.includes('getComputedStyle') ||
        message.includes('loop completed')) {
      event.preventDefault()
    }
  }
})

// 拦截控制台错误
const originalConsoleError = console.error
console.error = function (...args) {
  const message = args.join(' ')
  if (message.includes('ResizeObserver') || 
      message.includes('loop completed') ||
      message.includes('overlay')) {
    return // 完全忽略
  }
  originalConsoleError.apply(console, args)
}

// 创建应用实例
const app = createApp(App)

// 注册Element Plus图标
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
  app.component(key, component)
}

// 使用插件
app.use(store)
app.use(router)
app.use(ElementPlus, {
  locale: zhCn
})

// 初始化用户认证状态
store.dispatch('initializeAuth')

// 挂载应用
app.mount('#app')